package code.example.base.cpu.gc;

import code.example.tool.FixedThreadPool;
import code.example.tool.LogFactory;

import java.util.ArrayList;
import java.util.List;

/**
 *  jvm参数：-Xmx5g -Xms5g -Xmn4g -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps  -Xss20m -XX:+PrintGCApplicationStoppedTime  -XX:+PrintGCApplicationConcurrentTime  -XX:+PrintSafepointStatistics  -XX:PrintSafepointStatisticsCount=1
 *  证明minor gc :stop the world (应用程序暂停)
 *  2018-02-27T22:05:45.513+0800: Application time: 4.3024348 seconds
 *  --应用运行了4.3s
 *  2018-02-27T22:05:45.521+0800: [GC (Allocation Failure) [PSYoungGen: 4187928K->0K(4182528K)] 4187936K->5883K(5231104K), 0.0256859 secs] [Times: user=0.08 sys=0.00, real=0.03 secs]
 *  --发生GC ,用时0.025s
 *  2018-02-27T22:05:45.547+0800: Total time for which application threads were stopped: 0.0342066 seconds, Stopping threads took: 0.0000193 seconds
 *  --应用程序暂停了0.034 ---Stopping threads took:  达到线程的安全点用时
 *  useTime:34--代码执行了0.034ms,包括了应用程序暂停时间（0.034s）其中有gc的时间（0.025s）
 */
public class GCRunner {
    List list = new ArrayList();
    public void fillMemory(int index,MemoryData memoryData){
        if(index>1000){
            while ( true ) {
                long startTime = System.currentTimeMillis();

                MemoryData md1 = new MemoryData();
                list.add(md1);
                if(list.size()>10000){
                    list.remove(list.size()-1);
                }
                long endTime = System.currentTimeMillis();
                long useTime = endTime - startTime;
                if(useTime >10){
                    LogFactory.getLog().info("useTime:"+useTime);
                }

               /* MemoryData md2 = new MemoryData();
                MemoryData md3 = new MemoryData();
                MemoryData md4 = new MemoryData();
                md1.setMemoryData(md2);
                md2.setMemoryData(md3);
                md3.setMemoryData(md4);*/
            }
        }else{
            MemoryData md1 = new MemoryData();
            memoryData.setMemoryData(md1);
            list.add(md1);
            fillMemory(++index,md1);
        }

    }
    public void test(){
        FixedThreadPool fixedThreadPool = new FixedThreadPool(1000);
        for(int i=0;i<1;i++){
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    fillMemory(0,new MemoryData());
                }
            });
        }
    }
    public static void main(String args []){
        new GCRunner().test();
    }
}
